<?php

namespace app\teacher\controller\learn;

use app\common\controller\Frontend;
use app\common\enums\LearnMeansEnum;
use app\common\model\banxi\learn\LearnReadingArticle;
use app\common\model\banxi\learn\LearnReadingArticleAnswer;
use app\common\model\banxi\learn\LearnReadingArticleExtend;
use app\common\model\banxi\learn\LearnReadingArticleMarkWord;
use app\common\model\banxi\learn\LearnSkRecord;
use app\common\model\banxi\course\CourseArticle;
use app\common\service\DouBaoAiArticleService;
use app\common\service\DouBaoAiArticleQuestionService;
use app\common\service\learn\LearnReadingArticleService;
use app\common\service\UploadService;
use think\facade\Log;

/*
 * 阅读理解
 * */
class TLearnReadingArticle extends Frontend
{
    protected array $noNeedLogin = [''];

    protected array $noNeedPermission = ['*'];

    public function initialize(): void
    {
        parent::initialize();
    }

    /*
     * 查询-阅读记录信息
     * */
    public function getReadingInfo()
    {
        $readingArticleId = $this->request->get('readingArticleId',0);

        $LearnReadingArticleModel = new LearnReadingArticle();
        $readingInfo = $LearnReadingArticleModel
            ->where(['id'=>$readingArticleId,'del'=>0])
            ->find();
        $readingInfo['canLimitAnswerNum'] = -1;//还可答题次数 -1 不限制
        $readingInfo['currentLimitAnswerNum'] = 0;//当前答题次数
        if ($readingInfo && $readingInfo['isSubmit'] && $readingInfo['skRecordId'] && $readingInfo['articleId']){
            $currentLimitAnswerNum = $LearnReadingArticleModel->countAnswerBySkRecordAndArticleId($readingInfo['skRecordId'],$readingInfo['articleId']);
            $readingInfo['currentLimitAnswerNum'] = $currentLimitAnswerNum;
            if ($readingInfo['limitAnswer']>0){
                $readingInfo['canLimitAnswerNum'] = $readingInfo['limitAnswer'] - $currentLimitAnswerNum;
            }
        }
        $this->ok('操作成功', $readingInfo);
    }

    /*
     * 查询-阅读文章信息
     * */
    public function getReadingExtendInfo()
    {
        $readingArticleId = $this->request->get('readingArticleId',0);
        $LearnReadingArticleExtendModel = new LearnReadingArticleExtend();
        $readingExtendInfo = $LearnReadingArticleExtendModel
            ->where(['readingArticleId'=>$readingArticleId])
            ->find();

        $this->ok('操作成功', $readingExtendInfo);
    }

    /*
     * 查询-阅读答题信息
     * */
    public function getReadingAnswerInfo()
    {
        $readingArticleId = $this->request->get('readingArticleId',0);

        $LearnReadingArticleAnswerModel = new LearnReadingArticleAnswer();
        $readingAnswerInfo = $LearnReadingArticleAnswerModel
            ->where(['readingArticleId'=>$readingArticleId])
            ->select();

        $this->ok('操作成功', $readingAnswerInfo);
    }

    /*
     * 查询-阅读标记单词信息
     * */
    public function getReadingMarkWordInfo()
    {
        $readingArticleId = $this->request->get('readingArticleId',0);

        $LearnReadingArticleModel = new LearnReadingArticle();
        $readingInfo = $LearnReadingArticleModel
            ->where(['id'=>$readingArticleId,'del'=>0])
            ->find();
        if(!$readingInfo){
            $this->ok('操作成功', []);
        }
        $LearnReadingArticleMarkWordModel = new LearnReadingArticleMarkWord();
        $where = [];
        if ($readingInfo['readingType']==1){
            $where[] = ['readingArticleId', '=', $readingInfo['id']];
        }elseif ($readingInfo['readingType']==2){
            if ($readingInfo['LearnMeans']==1){
                $where[] = ['articleId', '=', $readingInfo['articleId']];
            }else{
                $where[] = ['readingArticleId', '=', $readingInfo['id']];
            }
        }else{
            $this->ok('操作成功', []);
        }

        $list = $LearnReadingArticleMarkWordModel
            ->where($where)
            ->select();
        $this->ok('操作成功', $list);
    }

    /*
     * 加入生词
     * */
    public function markWord()
    {
        $readingArticleId = $this->request->post('readingArticleId',0);
        $word = $this->request->post('word','');
        if (!$word){
            $this->fail('单词不能为空','',0);
        }

        $LearnReadingArticleMarkWordModel = new LearnReadingArticleMarkWord();
        $result = $LearnReadingArticleMarkWordModel->markWord($readingArticleId,$word,$this->auth->id,null);

        $this->ok('操作成功');
    }

    /*
     * 开始AI阅读
     * */
    public function startAiReading()
    {
//        $params = $this->request->param(['skRecordId','wordIdList']);
        $skRecordId = $this->request->post('skRecordId',0);
        $wordIdList = $this->request->post('wordIdList',[]);
//        var_dump($skRecordId);
//        halt($wordIdList);
        $LearnReadingArticleModel = new LearnReadingArticle();
        $res = $LearnReadingArticleModel->startAiReading($skRecordId,$this->auth->id,$wordIdList);
//        $DouBaoAiArticleQuestionService = new DouBaoAiArticleQuestionService();
//        $articleContent = 'It was a bright sunny Saturday morning. I jumped out of bed, eager to spend the day with my friend. I grabbed my phone and dialed Lucy’s number. “Hi Lucy! The weather is perfect—would you like to go to the zoo with me today?” I asked, my voice brimming with excitement.
//Lucy’s reply came quickly, full of joy. “Yes! I’ve been wanting to see the new pandas,” she said. We met at the zoo entrance fifteen minutes later, each carrying a bag of popcorn. As we walked in, the sound of birds chirping and children laughing filled the air.
//We spent the afternoon exploring: watching lions lounge in the sun, giraffes stretch their long necks to eat leaves, and penguins waddle in their icy enclosure. The highlight was feeding the rabbits—one fluffy brown rabbit hopped to Lucy, and she held out a carrot. It nibbled gently, and she giggled. “Look, it likes you!” I said, pointing to the rabbit.
//As the day came to an end, we sat on a bench, tired but happy. “Thank you for inviting me,” Lucy said. “I had so much fun at the zoo.” I smiled and replied, “Me too! Would you want to come again next weekend?” She nodded, her eyes shining. “Absolutely!”
//';
//        $res = $DouBaoAiArticleQuestionService->getArticleQuestionByContent($articleContent);

        $this->ok('操作成功',$res);
    }

    /*
     * 开始阅读
     * */
    public function startReading()
    {
        $skRecordId = $this->request->post('skRecordId',0);
        $articleId = $this->request->post('articleId',0);

        $trainerId = $this->auth->id;
        $studentId = null;
        $learnMeans = LearnMeansEnum::E2; // 默认为练习模式（对应 LearnMeans.E2）

        // 如果提供了上课记录ID
        if ($skRecordId) {
            // 查询上课记录
            $learnSkRecord = LearnSkRecord::where('id', $skRecordId)->find();

            // 验证上课记录是否存在
            if (empty($learnSkRecord)) {
                $this->fail('上课记录不存在');
            }

            // 验证教练ID是否匹配
            if ($learnSkRecord['trainerId'] != $trainerId) {
                $this->fail('上课记录不存在');
            }

            // 获取学生ID
            $studentId = $learnSkRecord['studentId'];
            $learnMeans = LearnMeansEnum::E1; // 设置为教学模式（对应 LearnMeans.E1）
        }
        $LearnReadingArticleService = new LearnReadingArticleService();
        $result = $LearnReadingArticleService->startReading($skRecordId, $studentId, $trainerId, $articleId, $learnMeans);

        if (!$result){
            $this->fail($LearnReadingArticleService->getError());
        }
        $this->ok('提交成功', $result);
    }


    /*
     * 答案提价
     * */
    public function answerQuestion()
    {
        $readingArticleId = $this->request->post('readingArticleId');
        $useTime = $this->request->post('useTime');
        $answerList = $this->request->post('answerList');

        if (!$readingArticleId){
            $this->fail('阅读文章记录ID不能为空');
        }
        $trainerId = $this->auth->id;

        $LearnReadingArticleService = new LearnReadingArticleService();
        $result = $LearnReadingArticleService->answerQuestion($readingArticleId, $trainerId, null, $useTime, $answerList);

        if (!$result){
            $this->fail($LearnReadingArticleService->getError());
        }
        $this->ok('提交成功', $result);
    }

    /*
     * 查询-下一章节文章ID
     * */
    public function getNextReadingArticleId()
    {
        $articleId = $this->request->get('articleId');
        $CourseArticleModel = new CourseArticle();
        $nextArticleId = $CourseArticleModel->getNextId($articleId);

        $this->ok('提交成功', $nextArticleId);
    }
}